<template>
  <div>
    <page-header title="用户管理">
      <n-button type="primary" @click.stop="handleClickAdd">新增</n-button>
    </page-header>
    <div class="mt-[16px]">
      <n-grid x-gap="12" :cols="24">
        <n-gi :span="6">
          <n-input placeholder="请输入用户姓名" clearable v-model:value="paginationResult.realname"
            @keyup.enter="handleSearch" />
        </n-gi>
        <n-gi :span="6">
          <n-input placeholder="请输入用户登录账号" v-model:value="paginationResult.username" clearable
            @keyup.enter="handleSearch" />
        </n-gi>
        <n-gi :span="12">
          <n-select placeholder="请选择用户角色" clearable multiple :options="rolesList" value-field="id"
            label-field="roleName" v-model:value="paginationResult.roleIds" @change="handleSearch" />
        </n-gi>
      </n-grid>
      <div class="mt-[16px]"></div>
      <BasicTable :table-props="tableResult" :columns="columnsWithoutRoles" :pagination-props="paginationResult"
        :style="{ height: `66vh` }" @changePageSize="handleChangePage" :row-props="rowProps">
        <template #expandable="{ row }">
          <div v-if="row.roles && row.roles.length > 0" class="role-container">
            <div v-for="roleItem in row.roles" :key="roleItem.id" class="role-item">
              <div class="role-header cursor-pointer">
                <n-tag class="mr-1" :bordered="false" size="small">{{ roleItem.roleName }}</n-tag>
              </div>
              <div v-if="expandedRoles.has(roleItem.id)" class="role-users">
                <n-spin v-if="loadingRoleUsers.get(roleItem.id)" size="small" />
                <template v-else>
                  <div v-if="roleUsersMap.get(roleItem.id)?.length" class="pl-4 pt-2 text-xs text-gray-500">
                    <div v-for="user in roleUsersMap.get(roleItem.id)" :key="user.id" class="mb-1">
                      {{ user.realname }} ({{ user.username }})
                    </div>
                  </div>
                  <n-empty v-else size="small" description="暂无用户" />
                </template>
              </div>
            </div>
          </div>
        </template>
      </BasicTable>
    </div>
    <UserModal :action-type="actionType" v-model:show="showUserModal" :title="userModalTitle" :user-detail="userDetail"
      @edit-success="handleEditSuccess" @create-success="handleCreateSuccess" @close="handleToggleShowUserModal(false)"
      @cancel="handleToggleShowUserModal(false)" />
  </div>
</template>
<script setup lang="ts">
import { h, onMounted, ref, reactive } from "vue";
import { NButton, NIcon, NTag, NSpin, NEmpty } from "naive-ui";
import { cloneDeep, debounce, get } from "lodash-es";
import { CreateOutline, ChevronDownOutline, ChevronUpOutline } from "@vicons/ionicons5";
import { useTableHook } from "@/components/normal/basicTable/useTableHook";
import { UserModal, userUserModal } from "@/components/biz/userModal/index";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import { getUserList, getAllClientRoles, getUsersByRoleId } from "@/api/user/user.api";

// 存储展开的角色行
const expandedRoles = reactive(new Set());
// 存储角色用户数据
const roleUsersMap = reactive(new Map());
// 加载状态
const loadingRoleUsers = reactive(new Map());

// 基础列定义（不包含角色列）
const columnsWithoutRoles = [
  {
    title: "#",
    type: "index",
    key: "key",
    render: (row: any, index: number) => {
      // 检查是否有角色
      const hasRoles = row.roles && row.roles.length > 0;
      
      // 如果没有角色，只返回序号
      if (!hasRoles) {
        return `${index + 1}`;
      }
      
      // 如果有角色，返回展开按钮和序号
      return h('div', { class: 'flex items-center' }, [
        h(
          NButton,
          {
            size: "tiny",
            quaternary: true,
            class: 'mr-1',
            onClick: (e) => {
              e.stopPropagation();
              // 获取第一个角色的ID作为展开标识
              const roleId = row.roles[0].id;
              handleToggleRoleExpand(roleId);
            }
          },
          {
            icon: () => h(NIcon, null, {
              default: () => h(expandedRoles.has(row.roles[0]?.id) ? ChevronUpOutline : ChevronDownOutline),
            }),
          }
        ),
        `${index + 1}`
      ]);
    },
  },
  {
    title: "姓名",
    key: "realname",
  },
  {
    title: "登录账号",
    key: "username",
  },
  {
    title: "操作",
    key: "actions",
    align: "right",
    render: (row: any) => {
      return [
        h(
          NButton,
          {
            size: "small",
            type: "primary",
            secondary: true,
            onClick: () => {
              handleClickEdit(row);
            },
          },
          {
            icon: () =>
              h(NIcon, null, {
                default: () => h(CreateOutline),
              }),
          }
        ),
      ];
    },
  },
];

// 处理角色展开/收起
const handleToggleRoleExpand = async (roleId: string) => {
  if (expandedRoles.has(roleId)) {
    expandedRoles.delete(roleId);
  } else {
    expandedRoles.add(roleId);

    // 如果没有加载过该角色的用户数据，则加载
    if (!roleUsersMap.has(roleId)) {
      loadingRoleUsers.set(roleId, true);
      // try {
      //   const result = await getUsersByRoleId(roleId);
      //   const users = get(result, "result") || [];
      //   roleUsersMap.set(roleId, users);
      // } catch (error) {
      //   console.error("获取角色用户失败", error);
      //   roleUsersMap.set(roleId, []);
      // } finally {
      //   loadingRoleUsers.set(roleId, false);
      // }
    }
  }
};

// 设置行属性
const rowProps = (row: any) => {
  return {
    style: "transition: all .3s",
  };
};

const {
  showUserModal,
  userModalTitle,
  userDetail,
  actionType,
  handleToggleShowUserModal,
} = userUserModal();

const { tableResult, paginationResult, getDataList } = useTableHook<any>({
  api: getUserList,
  queryForm: {
    realname: "",
    username: "",
    roleIds: [],
  },
});

const rolesList = ref<any[]>([]);

const handleClickAdd = () => {
  userModalTitle.value = "新增用户";
  actionType.value = ActionTypeEnum.ADD;
  userDetail.value = {};
  handleToggleShowUserModal(true);
};

const handleClickEdit = (payload: any) => {
  console.log(payload);
  userModalTitle.value = `编辑用户-${payload.realname}`;
  actionType.value = ActionTypeEnum.EDIT;
  userDetail.value = cloneDeep(payload);
  handleToggleShowUserModal(true);
};

const handleGetAllClientRoles = async () => {
  const result = await getAllClientRoles();
  rolesList.value = get(result, "result") || [];
};

const handleEditSuccess = () => {
  handleToggleShowUserModal(false);
  getDataList();
};

const handleCreateSuccess = () => {
  handleToggleShowUserModal(false);
  handleSearch();
};

const handleSearch = debounce(function () {
  paginationResult.page = 1;
  getDataList();
}, 200);

const handleChangePage = debounce(function (val) {
  paginationResult.pageSize = val;
  console.log(paginationResult);
  getDataList();
}, 200);

const init = () => {
  getDataList();
  handleGetAllClientRoles();
};

onMounted(() => {
  init();
});
</script>

<style scoped>
.role-container {
  padding: 8px 0;
}

.role-item {
  margin-bottom: 8px;
}

.role-header {
  display: flex;
  align-items: center;
}

.role-users {
  margin-top: 4px;
}
</style>
